package com.zlq.add.Thread;

import java.util.concurrent.CountDownLatch;

/**
 * 特征：
 * 1.必须发生指定数量的事件后才可以继续运行(比如赛跑比赛，裁判喊出3,2,1之后大家才同时跑)
 * 2.CountDownLatch(int count):必须发生count个数量才可以打开锁存器
 * 3.await：等待锁存器
 * 4.countDown：触发事件
 */

public class CountDownLatchThread {
    public static void main(String[] args) {
        //创建一个计数栓，数三个数
        CountDownLatch countDownLatch = new CountDownLatch(3);
        //有A,B,C个运动员
        new Athlete(countDownLatch, "A").start();
        new Athlete(countDownLatch, "B").start();
        new Athlete(countDownLatch, "C").start();

        //倒计时
        for (int i = 0; i < 3; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(3 - i);
            //倒计时触发事件 -1
            countDownLatch.countDown();
            if (i == 2){
                System.out.println("开始......");
            }

        }

    }
}

//运动员
class Athlete extends Thread {
    //倒计时锁存器
    private CountDownLatch countDownLatch;

    public Athlete(CountDownLatch countDownLatch, String name) {
        setName(name);
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        System.out.println(getName() + "在等待...");
        try {
            //等待锁存器
            countDownLatch.await();
            for (int i = 0; i < 3; i++) {
                System.out.println("运动员："+getName() + ":" + i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
